# """
# 公共类
# """
# import os
# import sys
# import shutil
# import zipfile


# # 判断文件夹是否存在，不存在则创建

# def create_folder_if_not_exists(folder_path):  # folder_path 文件夹路径
#     if not os.path.exists(folder_path):
#         os.makedirs(folder_path)


# def count_files_in_zip(zip_file_path):
#     if not os.path.exists(zip_file_path):
#         return 0
#     with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
#         num_files = len(zip_ref.namelist())
#     return num_files


# def find_index(lst, str):
#     for i in range(len(lst)):
#         if str in lst[i]:
#             return i
#     return -1


# def create_zip_file(df, directory, output_filename):
#     base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
#     temp_dir = os.path.join(base_path, 'temp_pdf')
#     os.makedirs(temp_dir, exist_ok=True)
#     arrpdf = os.listdir(directory)
#     temppdf = os.listdir(temp_dir)
#     nolist = []
#     mail_Attachments = []

#     for r in df.iter_rows():
#         if r[1] == '': # CertificateCode
#             continue
#         certificateCode_list = r[1].split(',')
#         itempdflist = []
#         for certificateCode in certificateCode_list:
#             bo = find_index(temppdf, certificateCode)
#             if bo == -1:
#                 index = find_index(arrpdf, certificateCode)
#                 if index != -1:
#                     temp_pdf_path = os.path.join(temp_dir, arrpdf[index])
#                     with open(os.path.join(directory, arrpdf[index]), 'rb') as f_src, open(temp_pdf_path,
#                                                                                            'wb') as f_dst:
#                         shutil.copyfileobj(f_src, f_dst)
#                         temppdf.append(arrpdf[index])
#                         bo = len(temppdf) - 1
#             if bo > -1:
#                 itempdflist.append(temppdf[bo])
#             else:
#                 nolist.append({
#                     "Item": r[0],
#                     "CertificateCode": certificateCode
#                 })
#         if itempdflist:
#             itempdfzippath = os.path.join(output_filename, r[0] + '.zip')
#             if count_files_in_zip(itempdfzippath) != len(itempdflist):
#                 with zipfile.ZipFile(itempdfzippath, 'w') as zipf:
#                     for itempdf in itempdflist:
#                         zipf.write(os.path.join(temp_dir, itempdf), arcname=itempdf)
#             mail_Attachments.append(itempdfzippath)

#     return nolist, mail_Attachments



"""
公共类
"""
import os
import sys
import shutil
import zipfile


# 判断文件夹是否存在，不存在则创建

def create_folder_if_not_exists(folder_path):  # folder_path 文件夹路径
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)


def count_files_in_zip(zip_file_path):
    if not os.path.exists(zip_file_path):
        return 0
    with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
        num_files = len(zip_ref.namelist())
    return num_files


def find_index(lst, str):
    for i in range(len(lst)):
        if str in lst[i]:
            return i
    return -1


def create_zip_file(df, directory, output_filename):
    base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    temp_dir = os.path.join(base_path, 'temp_pdf')
    os.makedirs(temp_dir, exist_ok=True)
    arrpdf = os.listdir(directory)
    temppdf = os.listdir(temp_dir)
    nolist = []
    mail_Attachments = []

    for row in df.iter_rows():
        # Polars DataFrame 使用 iter_rows() 迭代
        cert_codes = str(row[0]).split(',')
        for cert_code in cert_codes:
            cert_code = cert_code.strip()
            
            # 查找对应的文件
            matching_files = [f for f in os.listdir(directory) if cert_code in f]
            
            if matching_files:
                for file in matching_files:
                    # 检查文件是否为RAR格式
                    if file.lower().endswith('.rar'):
                        # RAR文件直接复制到目标目录
                        source_path = os.path.join(directory, file)
                        dest_path = os.path.join(output_filename, file)
                        shutil.copy2(source_path, dest_path)
                        mail_Attachments.append(dest_path)
                        continue
                    
                    # 其他文件继续原来的ZIP打包逻辑
                    source_path = os.path.join(directory, file)
                    temp_path = os.path.join(temp_dir, file)
                    with open(source_path, 'rb') as f_src, open(temp_path, 'wb') as f_dst:
                        shutil.copyfileobj(f_src, f_dst)
                        temppdf.append(file)
                        bo = len(temppdf) - 1
                    if bo > -1:
                        itempdflist.append(temppdf[bo])
                    else:
                        nolist.append({
                            "Item": row[0],
                            "CertificateCode": cert_code
                        })
            if itempdflist:
                itempdfzippath = os.path.join(output_filename, row[0] + '.zip')
                if count_files_in_zip(itempdfzippath) != len(itempdflist):
                    with zipfile.ZipFile(itempdfzippath, 'w') as zipf:
                        for itempdf in itempdflist:
                            zipf.write(os.path.join(temp_dir, itempdf), arcname=itempdf)
                mail_Attachments.append(itempdfzippath)

    return nolist, mail_Attachments
